

<template>
    <view class="groupMembers">
        <!-- <image
            class="psa"
            style="width:750rpx;height:834rpx;top:0;left:0;right:0;z-index:1;"
            src="../../static/bg1.jpg"
            mode=""
        ></image> -->
        <view
            style="
                background: #fff;
                width: 750rpx;
                position: fixed;
                z-index: 100;
            "
            :style="{ height: systemInfo.statusBarHeight + 'px' }"
        ></view>
        <view
            class="slim_header d-flex a-center j-center"
            style="border-bottom: none"
            :style="{ top: systemInfo.statusBarHeight + 'px' }"
        >
            <view class="left_box" @tap="goBack">
                <image src="/static/center/back.png" class="back"></image>
            </view>
            <view class="title d-flex a-center j-between">移除成员</view>
            <view class="right_box">
                <!-- <image src="/static/center/dian.png" class="dian"></image> -->
            </view>
        </view>

        <view
            class="search_box d-flex a-center j-center"
            :style="{ top: `calc(  100rpx + ${systemInfo.statusBarHeight}px)` }"
        >
            <view class="search d-flex a-center">
                <i
                    class="tmicon tmicon-search"
                    style="color: #ccc; font-size: 30rpx"
                ></i>
                <input
                    type="text"
                    class="inp"
                    @input="search"
                    v-model="searchText"
                    placeholder="好友昵称"
                    placeholder-style="color:#ccc;font-size:25rpx;"
                />
            </view>
        </view>

        <scroll-view
            :scroll-y="true"
            class="content"
            :style="{ top: `calc(  180rpx + ${systemInfo.statusBarHeight}px)` }"
        >
            <view class="box_view">
                <view class="list" v-if="groupMembers.length">
                    <view
						
                        class="psr row d-flex d-r a-center"
                        v-for="m in groupMembers"
                        :key="m.userId"
                        @tap="toggleCheck(m)"
						
                    >
                        <view class="head_box psr">
                            <userhead
                                width="95"
                                height="95"
                                :saveKey="m.userId"
                                :isVip="m.isVip"
                                :src="m.userPhoto"
                            />
							<view class="role" v-if="m.role === 'Admin'"
							    >管理员</view
							>
                            <!-- <cacheimg class="head" :src="f.profile.avatar" :saveKey="f.userID"></cacheimg>
                                <image
                                    v-if="f.profile.level===2"
                                    class="vip_icon w-center"
                                    src="/static/svip.png"
                                ></image>
                                <image
                                    v-if="f.profile.level===1"
                                    class="vip_icon w-center"
                                    src="/static/vip.png"
                                ></image> -->
                        </view>
                        <view class="name d-flex a-center">
                            <rich-text :nodes="m.nodes"></rich-text>
                        </view>
                        <view class="line"></view>

                        <view class="visitor d-flex a-center j-center" v-if="m.role==='Tourist'">游客</view>

                        <view 
							v-if="role != 'Admin' || m.role != 'Admin'"
							class="check_box d-flex a-center j-center h-center" 
							:class="{checked:isSelected(m)}"
							
						>
                            <image
                                v-if="isSelected(m)"
                                class="checkImg"
                                src="/static/checked.png"
                                mode=""
                            />
                        </view>
                    </view>
                </view>

                <view class="nodata" style="position:absolute;top:0;left:0;bottom:0;" v-if="!groupMembers.length">
                    <image class="nodata-img" src="/static/img/nodata.png" alt="" />
                    <view class="text">竟然什么都没有~</view>
                </view>
            </view>
        </scroll-view>

        <view class="bottom_box">
            <view class="d-flex a-center j-between">
				<!--
                <scroll-view
                    class="selected"
                    :scroll-x="true"
                    :scroll-y="false"
                    :show-scrollbar="false"
                    :enable-flex="true"
                >
                    <view class="selected_box" v-if="selected.userId">
                        <cacheimg
                            class="userhead"
                            style="border: 1px solid #ddd"
                            :saveKey="selected.userId"
                            :src="selected.userPhoto"
                            mode="aspectFill"
                        ></cacheimg>
                    </view>
                </scroll-view>
				-->
                <view class="right_area d-flex d-c">
                    <view
                        @tap="KickOut"
                        class="btn1 d-flex a-center j-center"
                        :class="{ disabled: selected.length === 0 }"
                    >
                        移除
                    </view>
                </view>
            </view>
             <view class="heightBox"></view>
        </view>

    </view>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { onReady, onShow, onLoad } from "@dcloudio/uni-app";
import { userData as userDataStore } from "@/store/userData";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import { getGroupMember,getCircleDetail,groupKickOut } from "@/api/api";
import { getFriendList,getGroupMemberList,getGroupProfile } from "@/hooks/imHooks";
import cacheimg from "@/components/cacheimg.vue";
import { imStore as imStore1 } from "@/store/imStore";
import userhead from "@/components/userhead.vue";
import { wait,showLoading,closeLoading } from "@/utils/utils"

const imStore: any = imStore1();
/*
const goUserDetail = (userId: any) => {
    uni.navigateTo({
        url: `/pages/personalCenter/personalCenter?userId=${userId}`,
    });
};
*/
const searchText = ref("");
const groupMembers:any = ref([]);
const all_groupMembers:any = ref([]);
//const friends = ref([]);
//const all_friends = ref([]);
//const userData: any = userDataStore();
const systemInfo: any = systemInfoStore();
const selected:any = ref([]);
const groupId = ref('');


const  goBack = () => {
	uni.navigateBack();
};
const isSelected = (m:any) => {
	return selected.value.includes(m);
}
const toggleCheck = (m:any) => {
	if(role.value == 'Admin' && m.role == 'Admin')return;
	
	
	if (selected.value.includes(m)) {  
	    // 如果元素存在，则删除它  
	    const index = selected.value.indexOf(m);  
	    if (index !== -1) {  
	        selected.value.splice(index, 1);  
	    }  
	} else {  
	    // 如果元素不存在，则添加它  
	    selected.value.push(m);  
	}
	console.log(selected.value)
    //selected.value = m;
};
/*
const formatRole = (role)=>{
    if(role==='Owner'){
        return '群主';
    }

    if(role==='Admin'){
        return '管理员';
    }
    if(role==='Member'){
        return '成员';
    }
    if(role==='Tourist'){
        return '游客';
    }

    return  '未知'
}
*/

const getFriends = async () => {
    const res: any = await getFriendList();
    const { code, data } = res;
    if (code !== 0) {
        return;
    }
    imStore.setFriends(data);
};

const groupDetail = ref({});


const getDetail = async (groupId: string) => {
    const res: any = await getCircleDetail({ groupId });
    const { flag, data } = res;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: "获取群资料失败",
            duration: 1500,
        });
        return;
    }


    groupDetail.value = data;
};


const initData = () => {


    const friends = imStore.friends;


    all_groupMembers.value.forEach((item:any)=>{
        friends.forEach((f:any)=>{
            if(f.userID === item.userId){
                item.remark = f.remark;
            }
        })
    })



    const clone_groupMembers = JSON.parse(JSON.stringify(all_groupMembers.value));
    
    groupMembers.value = clone_groupMembers.map((item:any) => {
        let color = "#333";
        if (item.isVip) {
            color = "#F19945";
        }

        return {
            ...item,
            nodes: `<div style="color:${color};font-weight:400;">${
                item.remark || item.userName
            }</div>`,
        };
    });
};

const search = () => {
    if (!searchText.value) {
        initData();
        return;
    }

    groupMembers.value = all_groupMembers.value.filter((item:any) => {
        const str = item.remark || item.userName;
        if (str.toLowerCase().search(searchText.value.toLowerCase()) !== -1) {
            return true;
        } else {
            return false;
        }
    });

    matchTextHighLight();
};

const matchTextHighLight = () => {
    const reg = new RegExp(searchText.value, "gi");
    groupMembers.value = groupMembers.value.map((item:any) => {
        const obj = {
            ...item,
        };
        // const str = `<div style="color:#555;">${item.profile.nick}</div>`;
        const str = item.remark || item.userName;
        const nodes = `<div style="color:#555;font-weight:400;">${str.replace(
            reg,
            (s: any) => {
                return `<span style="color:#23e2a6">${s}</span>`;
            }
        )}</div>`;
        obj.nodes = nodes;
        return obj;
    });
};


let offset = 0;
const getGroupMembers = async (groupId: string) => {
    if (!offset) {
        IM_STORE.clearGroupMembers();
    }

    if (!uni.$chat_isSDKReady) {
        setTimeout(() => {
            getGroupMembers(groupId);
        }, 200);
        return;
    }

    const res: any = await getGroupMemberList(groupId, offset);
    const { code, data } = res;
    console.log("getGroupMembers");
    console.log(data.memberList);
    if (code !== 0) {
        uni.showToast({
            icon: "none",
            title: "获取成员列表失败",
            duration: 1500,
        });
        return;
    }
    offset++;
    IM_STORE.pushGroupMembers(data.memberList);
    if (data.memberList.length === 500) {
        getGroupMembers(groupId);
    }
};

const reqGroupMember = async (groupId: string) => {
    const res: any = await getGroupMember({ groupId });
    const { flag, data } = res;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: "获取成员列表失败",
            duration: 1500,
        });
    }

    console.log("data.list");
    console.log(data.list);

    if(selected.value.userId){
        if(data.list.every((item:any)=>item.userId!==selected.value.userId)){
            selected.value={};
        }
    }

    all_groupMembers.value = data.list.filter((item:any)=>item.role!=='Owner');
};
/*
const sendCustomMessage = (f:any,payload:any) => {

    return new Promise((resolve,reject) => {
        try {
                let message = uni.$TUIKit.createCustomMessage({
                to: f.userID,
                conversationType: 'C2C',
                payload,
            });
            // 3. 发送消息
            uni.$TUIKit.sendMessage(message).then(res=>{
                resolve(res);
            }).catch((err)=>{
                resolve(err);
            });
            
        } catch (error) {
            resolve(error);
        }
    })
};
*/
let loading = false;
/*
const kickOut = async() => {

    if(loading){
        return
    }
    loading = true;


    if(!selected.value.userId){
        uni.showToast({
            icon: "none",
            title: "请选择成员",
            duration: 1500,
        });

        loading = false;
        return
    }
    uni.navigateTo({
        url: `/pages/TUIKit/TUIPages/TUIGroup/groupPages/kickoutSubmit?userName=${selected.value.userName}&userId=${selected.value.userId}&groupId=${groupId.value}`,
    });
};
*/
const role = ref("Member");
const groupProfile = ref({});
const GetGroupProfile = async (groupId: string) => {
    const res: any = await getGroupProfile(groupId);
    const { code, data } = res;
    if (code !== 0) {
        uni.showToast({
            icon: "none",
            title: "获取群信息失败",
            duration: 1500,
        });
        return;
    }
    groupProfile.value = data.group;
	role.value = data.group.selfInfo.role;
};
//确认删除
//let loading = false;
const KickOut =async ()=>{
	if(selected.value.length === 0 )return;
    if(loading){
        return;
    }
	/*
	if(!selected.value.userId){
        uni.showToast({
            icon: "none",
            title: "请选择成员",
            duration: 1500,
        });

        loading = false;
        return
    }
	*/
    loading = true;
    showLoading('移除中...');
	
	let userIds = selected.value.map((item:any) => item.userId);
	
    const params = {
		ids:userIds,
        //userId:selected.value.userId,
        groupId:groupId.value,
        isJoinBlacklist:0,
    }
    const res:any = await groupKickOut(params).catch(()=>{
        closeLoading();
        loading=false;
    })

    loading=false;
    const {flag} = res;

    if(flag!==1){
        uni.showToast({
            icon: "none",
            title: "移除成员失败，请稍后再试",
            duration: 2000,
        });
        return;
    }

    setTimeout(()=>{
        uni.showToast({
            icon: "success",
            title: "已移除成员",
            duration: 2000,
        });
    },2000)


    setTimeout(()=>{
        goBack();
    },3000)

}
onReady(() => {});

onLoad(async (option: any) => {
    if (option.groupID) {
        groupId.value = option.groupID;
		await GetGroupProfile(groupId.value)
    }
});

onShow(() => {
    loading = false;
    Promise.all([reqGroupMember(groupId.value), getFriends(),getDetail(groupId.value)]).then(() => {
        initData();
    });
});
</script>

<style lang="scss" scoped>
.groupMembers {
    width: 750rpx;
    height: 100vh;
    background: #fff;

    .search_box {
        position: fixed;
        width: 750rpx;
        background: #fff;
        padding-bottom: 20rpx;

        .search {
            width: 690rpx;
            height: 70rpx;
            border-radius: 10rpx;
            background: #f5f5f5;
            padding: 0 30rpx;
            .inp {
                width: 570rpx;
                margin-left: 20rpx;
                font-size: 25rpx;
            }
        }
    }

    .bottom_box {
        position: fixed;
        width: 750rpx;
        left: 0;
        background-color: #fff;
        padding: 0 30rpx;
        padding-top:20rpx;
        bottom:0;
        .selected {
            height: 80rpx;
            width: 100rpx;
            white-space: nowrap;

            .selected_box {
            }

            .userhead {
                width: 80rpx;
                height: 80rpx;
                border-radius: 10rpx;
                margin-right: 10rpx;
            }
        }

        .right_area {
            flex:1;
            padding-left:10rpx;
            .btn1 {
                font-weight: 600;
                padding: 0 30rpx;
                height: 80rpx;
                background: linear-gradient(318deg, #64f1c5 0%, #29dba3 100%);
                color: #fff;
                font-size:32rpx;
                border-radius: 20rpx;
                &.disabled {
                    color: #999;
                    background: #eee;
                }

                &:active{
                    opacity: .7;
                }
            }
        }

        .heightBox{
            width:750rpx;
            min-height:20rpx;
            height:constant(safe-area-inset-bottom);
            height:env(safe-area-inset-bottom);
        }
    }

    .content {
        position: absolute;
        width: 750rpx;
        left: 0;
        right: 0;
        bottom: calc(constant(safe-area-inset-bottom) + 120rpx);
        bottom: calc(env(safe-area-inset-bottom) + 120rpx);
        background: #f5f5f5;

        .box_view {
            margin-top: 20rpx;
            background: #fff;
            .title {
                height: 60rpx;
                font-size: 28rpx;
                color: #333;
                font-weight: 400;
                padding: 0 30rpx;
            }
            .list {
            }
            .row {
                position: relative;
                padding: 0 30rpx;
                gap: 20rpx;
                height: 110rpx;
                .head_box {
                    width: 95rpx;
                    height: 95rpx;
                    .vip_icon {
                        width: 97rpx;
                        height: 43rpx;
                        bottom: -10rpx;
                    }
					.role {
					    position: absolute;
					    width: fit-content;
					    padding: 0 12rpx;
					    height: 25rpx;
					    background: #23e2a6;
					    border-radius: 12rpx;
					    font-size: 14rpx;
					    font-family: PingFangSC-Medium, PingFang SC;
					    font-weight: 400;
					    color: #ffffff;
					    text-align: center;
					    line-height: 25rpx;
					    left: 0;
					    right: 0;
					    bottom: 0;
					    margin: auto;
					}
                }
                .head {
                    width: 95rpx;
                    height: 95rpx;
                    border-radius: 50%;
                    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.1);
                    border: 3px solid #ffffff;
                }
                .name {
                    margin-left: 10rpx;
                    font-size: 34rpx;
                    color: $slim-text5;
                    &:active {
                    }
                }

                &:active {
                    background: #f5f5f5;
                }
                .line {
                    position: absolute;
                    height: 1px;
                    width: 600rpx;
                    left: 130rpx;
                    background-color: #f5f5f5;
                    bottom: 0;
                }
                .visitor{
                    position:absolute;
                    right:100rpx;
                    font-size:20rpx;
                    color:#F19945;
                    width: 60rpx;
                height: 32rpx;
                background: #FBE9D7;
                border-radius: 4rpx;

                }
                .joined {
                    color: #aaa;
                    font-size: 28rpx;
                }
                .check_box {
                    width: 40rpx;
                    height: 40rpx;
                    border: 2rpx solid #ddd;
                    right: 30rpx;
                    border-radius: 50%;
                    overflow:hidden;
                    background:#fff;
                    &.checked{
                        background:#23e2a6;
                        border: 2rpx solid #23e2a6;
                    }
                    .checkImg {
                        width: 28rpx;
                        height: 28rpx;
                    }
                }

                // &::before {
                //     content: "";
                //     position: absolute;
                //     left: 110rpx;
                //     right: 20rpx;
                //     bottom: 0;
                //     height: 1px;
                //     background-color: #f5f5f5;
                // }
            }
        }
    }
}

</style>
